package com.webchat.connect.service;


import com.webchat.common.bean.APIResponseBean;
import com.webchat.common.constants.ConnectConstants;
import com.webchat.common.service.WsSessionRegistryService;
import com.webchat.common.util.JsonUtil;
import com.webchat.domain.vo.request.mess.ChatMessageRequestVO;
import com.webchat.rmi.builder.FeignClientBuilder;
import com.webchat.rmi.connect.ConnectServiceClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserChatMessageSendService {


    @Autowired
    private WsSessionRegistryService sessionRegistryService;

    private String getSSEBizCode() {
        return ConnectConstants.ConnectBiz.getBizCode(ConnectConstants.ClientEnum.PC,
                ConnectConstants.AppEnum.WEB,
                ConnectConstants.BizEnum.CHAT);
    }

    public void doSend(ChatMessageRequestVO chatMessage) {

        String instanceHost = this.getReceiverSessionInstanceHost(getSSEBizCode(), chatMessage.getReceiverId());
        if (instanceHost == null) {
            return;
        }
        FeignClientBuilder<ConnectServiceClient> feignClientBuilder = new FeignClientBuilder(ConnectServiceClient.class);
        ConnectServiceClient connectServiceClient = feignClientBuilder.build(instanceHost);
        APIResponseBean<Boolean> apiResponseBean = connectServiceClient.doSend(chatMessage);
        log.info("RPC消息发送 ===> request:{}, response:{}",
                JsonUtil.toJsonString(chatMessage), JsonUtil.toJsonString(apiResponseBean));
    }

    private String getReceiverSessionInstanceHost(String bizCode, String receiverId) {
        return sessionRegistryService.getInstance(bizCode, receiverId);
    }
}
